package com.bonc.modules.business.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Logger;

import com.alibaba.fastjson.JSONObject;
import com.bonc.common.param.BaseParam;
import com.bonc.common.utils.*;
import com.bonc.modules.business.entity.TbCommonParamInfoEntity;
import com.bonc.modules.business.entity.TbWorkOrderCurrencyEntity;
import com.bonc.modules.business.entity.TbWorkOrderInfoEntity;
import com.bonc.modules.business.service.TbWorkOrderInfoService;
import io.swagger.annotations.Scope;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.bonc.modules.business.entity.TbWorkOederDistributionEntity;
import com.bonc.modules.business.service.TbWorkOederDistributionService;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 工单派发码表
 *
 * @author feiniao
 * @date 2021-10-11 11:16:14
 */
@RestController
@RequestMapping("business/tbworkoederdistribution")
public class TbWorkOederDistributionController {
    @Autowired
    private TbWorkOederDistributionService tbWorkOederDistributionService;

    @Autowired
    private TbWorkOrderInfoService tbWorkOrderInfoService;

    /**
     * 文件上传路径
     */
    @Value("${uploadPath}")
    private String uploadPath;

    /**
     * 文件下载路径
     */
    @Value("${downloadPath}")
    private String downloadPath;


    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("business:tbworkoederdistribution:list")
    public Result list(@RequestParam Map<String, Object> params){
        PageUtils page = tbWorkOederDistributionService.queryPage(params);

        return Result.ok().put("page", page);
    }

    /**
     * 前端页面展示查询工单全量工单信息
     * @param params
     * @return
     */
    @RequestMapping("/getOrderDistributionListByParam")
    public Result getOrderDistributionListByParam(@RequestBody Map<String, Object> params){
        String currPage = params.get("currPage").toString();
        params.put(Constant.PAGE, currPage);
        PageUtils page = tbWorkOederDistributionService.getOrderDistributionListByParam(params);
        return Result.ok().put("page", page);
    }

    /**
     * 前端页面展示查询申请单信息
     * @param params
     * @return
     */
    @RequestMapping("/getSqOrderDistributionListByParam")
    public Result getSqOrderDistributionListByParam(@RequestBody Map<String, Object> params){
        String currPage = params.get("currPage").toString();
        params.put(Constant.PAGE, currPage);
        PageUtils page = tbWorkOederDistributionService.getSqOrderDistributionListByParam(params);
        return Result.ok().put("page", page);
    }

    /**
     * 前端页面展示灭灯行动问题整改任务单
     */
    @RequestMapping("/getProblemOrderDistributionListByParam")
    public Result getProblemOrderDistributionListByParam(@RequestBody Map<String, Object> params){
        String currPage = params.get("currPage").toString();
        params.put(Constant.PAGE, currPage);
        PageUtils page = tbWorkOederDistributionService.getProblemOrderDistributionListByParam(params);
        return Result.ok().put("page", page);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{identifier}")
    //@RequiresPermissions("business:tbworkoederdistribution:info")
    public Result info(@PathVariable("identifier") String identifier){
        TbWorkOederDistributionEntity tbWorkOederDistribution = tbWorkOederDistributionService.getById(identifier);
        if(tbWorkOederDistribution.getIdentyType().equals("03")){
            StringBuffer buffer = new StringBuffer();
            String filename = "";
            if(!StringUtils.isBlank(tbWorkOederDistribution.getAttachList())) {
                String str[] = tbWorkOederDistribution.getAttachList().split("\\|");
                for (int j = 0; j < str.length; j++) {
                    filename = str[j].substring(10);

                    if (j == str.length - 1) {
                        buffer.append(filename);
                    } else {
                        buffer.append(filename + "|");
                    }
                }
                tbWorkOederDistribution.setAttachList(buffer.toString());
            }
        }
        return Result.ok().put("tbWorkOederDistribution", tbWorkOederDistribution);
    }

    /**
     * 保存
     * 获取界面用户创建的“灭灯行动”模块问题整改任务单 录入数据库
     */
    @RequestMapping("/save")
    public Result save(@RequestBody String content){
        TbWorkOederDistributionEntity distribution = JSONObject.parseObject(content,TbWorkOederDistributionEntity.class);
        Calendar calendar= Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmmss");
        String Identifier = dateFormat.format(calendar.getTime()) + "GZL" + "351" + AppUtils.getRandomReqNo();
        distribution.setIdentifier(Identifier);
        tbWorkOederDistributionService.save(distribution);

        //同时工单信息表需要录入一条数据
        TbWorkOrderInfoEntity tbWorkOrderInfo = new TbWorkOrderInfoEntity();
        tbWorkOrderInfo.setHandingTime(dateFormat1.format(calendar.getTime()));
        tbWorkOrderInfo.setIdentifier(distribution.getIdentifier());
        tbWorkOrderInfo.setState("01");
        tbWorkOrderInfo.setHandingDepartment("中国移动通信集团山西有限公司综合部");
        tbWorkOrderInfo.setHandingOpinions("xxx");
        tbWorkOrderInfo.setHandlerContactInfor("13834576868");
        tbWorkOrderInfo.setHandler("填报人");
        tbWorkOrderInfoService.save(tbWorkOrderInfo);

        //同时需要调用工单信息同步接口将工单信息同步给集团
        tbWorkOederDistributionService.SyncData(distribution);

        return Result.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public Result update(@RequestBody Map map){
        TbWorkOederDistributionEntity tbWorkOederDistribution = new TbWorkOederDistributionEntity();
        tbWorkOederDistribution.setIdentifier(map.get("identifier").toString());
        tbWorkOederDistribution.setParaList(JSONObject.toJSONString(map.get("paraList")));
        tbWorkOederDistributionService.updateById(tbWorkOederDistribution);
        return Result.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("business:tbworkoederdistribution:delete")
    public Result delete(@RequestBody String[] identifiers){
        tbWorkOederDistributionService.removeByIds(Arrays.asList(identifiers));

        return Result.ok();
    }

    /**
     * 工单派发接口
     * @param tbCommonParamValue
     * @return
     */
    //@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @PostMapping("/DispatchCSS")
    public ReplyCommon DispatchCSS(@RequestBody @Validated(BaseParam.list.class) TbCommonParamInfoEntity tbCommonParamValue) throws Exception {
        ReplyCommon res = tbWorkOederDistributionService.DispatchCSS(tbCommonParamValue);
        return res;
    }

    /**
     * 省端派发申请单到集团
     * @return
     */
    @RequestMapping("/DispatchCSService")
    public Result getDispatchCSService(@RequestBody TbWorkOederDistributionEntity tbWorkOederDistribution){
        AtomicReference<String> res = tbWorkOederDistributionService.postOrderDistributionService(tbWorkOederDistribution);
        return Result.ok().put("data", res);
    }

    /**
     * 获取accesstoken
     */
    @RequestMapping("/getTokenService")
    public Result getTokenService(){
        tbWorkOederDistributionService.getTokenService();
        return Result.ok();
    }

    @RequestMapping("/uploadFile")
    public String upload(@RequestParam("file") MultipartFile file) {
        System.out.println("开始执行上传文件");
        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }
        String result = tbWorkOederDistributionService.uploadLocal(file);
        return result;
    }

    @GetMapping("/downloadFile")
    public void downloadFile(String name, HttpServletResponse response) throws IOException {
        System.out.println("开始执行下载任务..." + name);
        String path = downloadPath + name;
        tbWorkOederDistributionService.downloadLocal(path,response);
    }

    @GetMapping("/generateOrderInfoDetail")
    public void generateOrderInfoDetail(){
        tbWorkOederDistributionService.generateOrderInfoDetail();
    }


    /**
     * 工单信息同步接口
     * @param distribution
     * @return
     * @throws Exception
     */
    @PostMapping("/SyncData")
    public Result SyncData(@RequestBody TbWorkOederDistributionEntity distribution) throws Exception {
        //TbWorkOederDistributionEntity distribution = JSONObject.parseObject(content,TbWorkOederDistributionEntity.class);
        AtomicReference<String> res = tbWorkOederDistributionService.SyncData(distribution);
        return Result.ok().put("data", res);
    }

}
